<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="queryParams" ref="queryFormRef">
        <el-form-item label="活动名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入活动名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="活动类型" prop="type">
          <el-select
            v-model="queryParams.type"
            placeholder="请选择活动类型"
            clearable
          >
            <el-option
              v-for="item in activityTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="活动状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择活动状态"
            clearable
          >
            <el-option
              v-for="item in activityStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="活动时间" prop="dateRange">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 活动统计卡片 -->
    <el-row :gutter="20" class="statistics-row">
      <el-col :span="6">
        <el-card class="statistics-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>进行中活动</span>
              <el-tag type="success">{{ statistics.ongoing }}</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="stat-item">
              <span>报名人数</span>
              <span class="value">{{ statistics.ongoingParticipants }}</span>
            </div>
            <div class="stat-item">
              <span>参与率</span>
              <span class="value">{{ statistics.ongoingRate }}%</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="statistics-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>即将开始</span>
              <el-tag type="warning">{{ statistics.upcoming }}</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="stat-item">
              <span>报名人数</span>
              <span class="value">{{ statistics.upcomingParticipants }}</span>
            </div>
            <div class="stat-item">
              <span>报名率</span>
              <span class="value">{{ statistics.upcomingRate }}%</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="statistics-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>已结束</span>
              <el-tag type="info">{{ statistics.completed }}</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="stat-item">
              <span>总参与人数</span>
              <span class="value">{{ statistics.completedParticipants }}</span>
            </div>
            <div class="stat-item">
              <span>平均参与率</span>
              <span class="value">{{ statistics.completedRate }}%</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="statistics-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>本月活跃度</span>
              <el-tag type="primary">{{ statistics.monthlyActivity }}</el-tag>
            </div>
          </template>
          <div class="card-content">
            <el-progress
              type="dashboard"
              :percentage="statistics.monthlyActivityRate"
              :color="activityColors"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作按钮区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <el-button type="primary" :icon="Plus" @click="handleAdd"
            >新增活动</el-button
          >
          <el-button type="success" :icon="Document" @click="handleExport"
            >导出数据</el-button
          >
        </div>
      </template>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="activityList"
        border
        style="width: 100%"
      >
        <el-table-column type="expand">
          <template #default="{ row }">
            <div class="activity-detail">
              <div class="detail-item">
                <h4>活动描述</h4>
                <p>{{ row.description }}</p>
              </div>
              <div class="detail-item">
                <h4>活动地点</h4>
                <p>{{ row.location }}</p>
              </div>
              <div class="detail-item" v-if="row.images && row.images.length">
                <h4>活动图片</h4>
                <div class="image-list">
                  <el-image
                    v-for="(img, index) in row.images"
                    :key="index"
                    :src="img"
                    :preview-src-list="row.images"
                    fit="cover"
                    class="activity-image"
                  />
                </div>
              </div>
              <div class="detail-item">
                <h4>报名情况</h4>
                <el-progress
                  :percentage="
                    (row.participants.length / row.maxParticipants) * 100
                  "
                  :format="format"
                  :status="getProgressStatus(row)"
                />
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="活动名称"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column prop="type" label="活动类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getActivityTypeTag(row.type)">
              {{ getActivityTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="活动时间" width="280">
          <template #default="{ row }">
            {{ formatDateTime(row.startTime) }} 至
            {{ formatDateTime(row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="活动状态"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getActivityStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="报名情况" width="150" align="center">
          <template #default="{ row }">
            {{ row.participants.length }}/{{ row.maxParticipants }}
            <el-tooltip
              v-if="row.participants.length >= row.maxParticipants"
              content="已满员"
              placement="top"
            >
              <el-icon class="full-icon"><Warning /></el-icon>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              :icon="Edit"
              @click="handleEdit(row)"
              v-if="['Draft', 'Pending'].includes(row.status)"
            >
              编辑
            </el-button>
            <el-button
              type="success"
              link
              :icon="List"
              @click="handleParticipants(row)"
            >
              报名管理
            </el-button>
            <el-button
              type="warning"
              link
              :icon="Message"
              @click="handleNotify(row)"
              v-if="row.participants.length > 0"
            >
              通知
            </el-button>
            <el-button
              type="danger"
              link
              :icon="Delete"
              @click="handleDelete(row)"
              v-if="['Draft', 'Pending'].includes(row.status)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNumber"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.type === 'add' ? '新增活动' : '编辑活动'"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="dialogFormRef"
        :model="dialog.form"
        :rules="dialog.rules"
        label-width="100px"
      >
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="dialog.form.name" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动类型" prop="type">
          <el-select
            v-model="dialog.form.type"
            placeholder="请选择活动类型"
            style="width: 100%"
          >
            <el-option
              v-for="item in activityTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="活动时间" prop="timeRange">
          <el-date-picker
            v-model="dialog.form.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="活动地点" prop="location">
          <el-input
            v-model="dialog.form.location"
            placeholder="请输入活动地点"
          />
        </el-form-item>
        <el-form-item label="参与人数" prop="maxParticipants">
          <el-input-number
            v-model="dialog.form.maxParticipants"
            :min="1"
            :max="999"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input
            v-model="dialog.form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入活动描述"
          />
        </el-form-item>
        <el-form-item label="活动图片" prop="images">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            multiple
            list-type="picture-card"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 报名管理对话框 -->
    <el-dialog
      v-model="participantsDialog.visible"
      title="报名管理"
      width="800px"
    >
      <el-table :data="participantsDialog.list" border style="width: 100%">
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="phone" label="联系电话" width="150" />
        <el-table-column prop="registrationTime" label="报名时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.registrationTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getParticipantStatusType(row.status)">
              {{ getParticipantStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              type="danger"
              link
              :icon="Close"
              @click="handleCancelParticipant(row)"
              v-if="row.status === 'Registered'"
            >
              取消报名
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 通知对话框 -->
    <el-dialog v-model="notifyDialog.visible" title="发送通知" width="600px">
      <el-form
        ref="notifyFormRef"
        :model="notifyDialog.form"
        :rules="notifyDialog.rules"
        label-width="100px"
      >
        <el-form-item label="通知标题" prop="title">
          <el-input
            v-model="notifyDialog.form.title"
            placeholder="请输入通知标题"
          />
        </el-form-item>
        <el-form-item label="通知内容" prop="content">
          <el-input
            v-model="notifyDialog.form.content"
            type="textarea"
            :rows="4"
            placeholder="请输入通知内容"
          />
        </el-form-item>
        <el-form-item label="通知方式" prop="methods">
          <el-checkbox-group v-model="notifyDialog.form.methods">
            <el-checkbox label="SMS">短信通知</el-checkbox>
            <el-checkbox label="Email">邮件通知</el-checkbox>
            <el-checkbox label="APP">APP推送</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="notifyDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleNotifySubmit">发送</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Search,
  Refresh,
  Plus,
  Edit,
  Delete,
  Document,
  List,
  Message,
  Warning,
  Close,
  View,
} from "@element-plus/icons-vue";
import {
  getActivities,
  createActivity,
  updateActivity,
  deleteActivity,
  getActivityStatistics,
  getParticipants,
  cancelParticipant,
  sendNotification,
} from "@/api/activity";
import { getToken } from "@/utils/auth";

// 活动类型选项
const activityTypes = [
  { label: "文化活动", value: "Cultural" },
  { label: "体育活动", value: "Sports" },
  { label: "公益活动", value: "Charity" },
  { label: "节日庆祝", value: "Festival" },
  { label: "其他", value: "Other" },
];

// 活动状态选项
const activityStatus = [
  { label: "草稿", value: "Draft" },
  { label: "待开始", value: "Pending" },
  { label: "进行中", value: "Ongoing" },
  { label: "已结束", value: "Completed" },
  { label: "已取消", value: "Cancelled" },
];

// 参与者状态选项
const participantStatus = [
  { label: "已报名", value: "Registered" },
  { label: "已取消", value: "Cancelled" },
  { label: "已参与", value: "Participated" },
  { label: "未到场", value: "Absent" },
];

// 查询参数
const queryParams = ref({
  name: "",
  type: "",
  status: "",
  dateRange: [],
  pageNumber: 1,
  pageSize: 10,
});

// 数据相关
const loading = ref(false);
const activityList = ref([]);
const total = ref(0);
const queryFormRef = ref();

// 统计数据
const statistics = ref({
  ongoing: 0,
  ongoingParticipants: 0,
  ongoingRate: 0,
  upcoming: 0,
  upcomingParticipants: 0,
  upcomingRate: 0,
  completed: 0,
  completedParticipants: 0,
  completedRate: 0,
  monthlyActivity: 0,
  monthlyActivityRate: 0,
});

// 活跃度颜色配置
const activityColors = [
  { color: "#f56c6c", percentage: 20 },
  { color: "#e6a23c", percentage: 40 },
  { color: "#5cb87a", percentage: 60 },
  { color: "#1989fa", percentage: 80 },
  { color: "#67c23a", percentage: 100 },
];

// 上传相关配置
const uploadUrl = import.meta.env.VITE_API_URL + "/api/file/upload";
const uploadHeaders = {
  Authorization: "Bearer " + getToken(),
};

// 对话框
const dialog = reactive({
  visible: false,
  type: "add",
  form: {
    name: "",
    type: "",
    timeRange: [],
    location: "",
    maxParticipants: 30,
    description: "",
    images: [],
  },
  rules: {
    name: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
    type: [{ required: true, message: "请选择活动类型", trigger: "change" }],
    timeRange: [
      { required: true, message: "请选择活动时间", trigger: "change" },
    ],
    location: [{ required: true, message: "请输入活动地点", trigger: "blur" }],
    maxParticipants: [
      { required: true, message: "请输入最大参与人数", trigger: "blur" },
    ],
    description: [
      { required: true, message: "请输入活动描述", trigger: "blur" },
    ],
  },
});

// 报名管理对话框
const participantsDialog = reactive({
  visible: false,
  currentActivity: null,
  list: [],
});

// 通知对话框
const notifyDialog = reactive({
  visible: false,
  currentActivity: null,
  form: {
    title: "",
    content: "",
    methods: ["APP"],
  },
  rules: {
    title: [{ required: true, message: "请输入通知标题", trigger: "blur" }],
    content: [{ required: true, message: "请输入通知内容", trigger: "blur" }],
    methods: [
      { required: true, message: "请选择至少一种通知方式", trigger: "change" },
    ],
  },
});

// 获取活动列表
const getList = async () => {
  try {
    loading.value = true;
    const [startDate, endDate] = queryParams.value.dateRange || [];
    const params = {
      ...queryParams.value,
      startDate,
      endDate,
    };
    delete params.dateRange;

    const res = await getActivities(params);
    activityList.value = res.items;
    total.value = res.total;
  } catch (error) {
    console.error("获取活动列表失败：", error);
  } finally {
    loading.value = false;
  }
};

// 获取统计数据
const getStatistics = async () => {
  try {
    const res = await getActivityStatistics();
    statistics.value = res;
  } catch (error) {
    console.error("获取统计数据失败：", error);
  }
};

// 搜索方法
const handleQuery = () => {
  queryParams.value.pageNumber = 1;
  getList();
};

// 重置搜索
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

// 新增活动
const handleAdd = () => {
  dialog.type = "add";
  dialog.form = {
    name: "",
    type: "",
    timeRange: [],
    location: "",
    maxParticipants: 30,
    description: "",
    images: [],
  };
  dialog.visible = true;
};

// 编辑活动
const handleEdit = (row) => {
  dialog.type = "edit";
  dialog.form = {
    ...row,
    timeRange: [row.startTime, row.endTime],
  };
  dialog.visible = true;
};

// 提交表单
const handleSubmit = async () => {
  try {
    const [startTime, endTime] = dialog.form.timeRange;
    const data = {
      ...dialog.form,
      startTime,
      endTime,
    };
    delete data.timeRange;

    if (dialog.type === "add") {
      await createActivity(data);
      ElMessage.success("创建成功");
    } else {
      await updateActivity(data.id, data);
      ElMessage.success("更新成功");
    }
    dialog.visible = false;
    getList();
    getStatistics();
  } catch (error) {
    console.error("保存失败：", error);
  }
};

// 删除活动
const handleDelete = (row) => {
  ElMessageBox.confirm("确定要删除该活动吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await deleteActivity(row.id);
      ElMessage.success("删除成功");
      getList();
      getStatistics();
    } catch (error) {
      console.error("删除失败：", error);
    }
  });
};

// 报名管理
const handleParticipants = async (row) => {
  try {
    participantsDialog.currentActivity = row;
    const res = await getParticipants(row.id);
    participantsDialog.list = res;
    participantsDialog.visible = true;
  } catch (error) {
    console.error("获取报名列表失败：", error);
  }
};

// 取消报名
const handleCancelParticipant = (row) => {
  ElMessageBox.confirm("确定要取消该用户的报名吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await cancelParticipant(participantsDialog.currentActivity.id, row.id);
      ElMessage.success("取消报名成功");
      handleParticipants(participantsDialog.currentActivity);
    } catch (error) {
      console.error("取消报名失败：", error);
    }
  });
};

// 发送通知
const handleNotify = (row) => {
  notifyDialog.currentActivity = row;
  notifyDialog.form = {
    title: `关于"${row.name}"的通知`,
    content: "",
    methods: ["APP"],
  };
  notifyDialog.visible = true;
};

// 提交通知
const handleNotifySubmit = async () => {
  try {
    await sendNotification(notifyDialog.currentActivity.id, notifyDialog.form);
    ElMessage.success("发送通知成功");
    notifyDialog.visible = false;
  } catch (error) {
    console.error("发送通知失败：", error);
  }
};

// 导出数据
const handleExport = async () => {
  try {
    const [startDate, endDate] = queryParams.value.dateRange || [];
    const params = {
      ...queryParams.value,
      startDate,
      endDate,
    };
    delete params.dateRange;

    await exportActivities(params);
    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败：", error);
  }
};

// 上传成功
const handleUploadSuccess = (response, file) => {
  dialog.form.images.push(response.url);
  ElMessage.success("上传成功");
};

// 上传失败
const handleUploadError = (error) => {
  console.error("上传失败：", error);
  ElMessage.error("上传失败");
};

// 上传前校验
const beforeUpload = (file) => {
  const isImage = /^image\//.test(file.type);
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error("只能上传图片文件!");
    return false;
  }
  if (!isLt5M) {
    ElMessage.error("图片大小不能超过 5MB!");
    return false;
  }
  return true;
};

// 分页方法
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val;
  getList();
};

const handleCurrentChange = (val) => {
  queryParams.value.pageNumber = val;
  getList();
};

// 获取活动类型标签
const getActivityTypeLabel = (type) => {
  return activityTypes.find((item) => item.value === type)?.label || type;
};

// 获取活动类型标签样式
const getActivityTypeTag = (type) => {
  const typeMap = {
    Cultural: "",
    Sports: "success",
    Charity: "warning",
    Festival: "danger",
    Other: "info",
  };
  return typeMap[type] || "info";
};

// 获取状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    Draft: "info",
    Pending: "warning",
    Ongoing: "success",
    Completed: "",
    Cancelled: "danger",
  };
  return statusMap[status] || "info";
};

// 获取活动状态标签
const getActivityStatusLabel = (status) => {
  return activityStatus.find((item) => item.value === status)?.label || status;
};

// 获取参与者状态标签类型
const getParticipantStatusType = (status) => {
  const statusMap = {
    Registered: "success",
    Cancelled: "info",
    Participated: "primary",
    Absent: "danger",
  };
  return statusMap[status] || "info";
};

// 获取参与者状态标签
const getParticipantStatusLabel = (status) => {
  return (
    participantStatus.find((item) => item.value === status)?.label || status
  );
};

// 获取进度条状态
const getProgressStatus = (row) => {
  if (row.participants.length >= row.maxParticipants) {
    return "success";
  }
  if (row.status === "Ongoing") {
    return "warning";
  }
  return "";
};

// 格式化进度条显示
const format = (percentage) => {
  return percentage === 100 ? "已满员" : `${percentage}%`;
};

// 格式化日期时间
const formatDateTime = (datetime) => {
  if (!datetime) return "-";
  return new Date(datetime).toLocaleString();
};

// 初始化
onMounted(() => {
  getList();
  getStatistics();
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;
  }

  .statistics-row {
    margin-bottom: 20px;

    .statistics-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .card-content {
        padding: 20px;

        .stat-item {
          display: flex;
          justify-content: space-between;
          margin-bottom: 10px;

          .value {
            font-weight: bold;
          }
        }
      }
    }
  }

  .table-card {
    .card-header {
      display: flex;
      gap: 10px;
    }

    .activity-detail {
      padding: 20px;

      .detail-item {
        margin-bottom: 20px;

        h4 {
          margin-bottom: 10px;
          color: #606266;
        }

        .image-list {
          display: flex;
          gap: 10px;

          .activity-image {
            width: 100px;
            height: 100px;
            border-radius: 4px;
            cursor: pointer;
          }
        }
      }
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }

    .full-icon {
      color: #f56c6c;
      margin-left: 5px;
    }
  }

  .upload-demo {
    :deep(.el-upload-list--picture-card) {
      .el-upload-list__item {
        width: 100px;
        height: 100px;
      }
    }
  }
}
</style>
